function open(entry) {
  if (!entry)
    return
  entry.file(function(file) {
    var fileReader = new FileReader();
    fileReader.onload = function() {
      var fileData = this.result;
      chrome.app.window.create('window.html', { hidden: true, bounds: { width: 195, height: 300 }}, function(appWindow) {
        appWindow.contentWindow.onload = function() {
          appWindow.contentWindow.viewer.init(fileData, function(blob) {
            sync(file.name, file);
            sync(file.name + '.png', blob);
          });
        };
      });
    }
    fileReader.readAsArrayBuffer(file);
  });
}

function sync(fileName, data) {
  chrome.syncFileSystem.requestFileSystem(function(fileSystem) {
    fileSystem.root.getFile(fileName, { create: true }, function(fileEntry) {
      fileEntry.file(function(syncedFile) {
        if (syncedFile.size != 0)
          return;
        fileEntry.createWriter(function(writer){
          writer.write(data);
        });
      });
    });
  });
}

chrome.app.runtime.onLaunched.addListener(function(launchData) {
  if (launchData.items) {
    for (var i = 0; i < launchData.items.length; i++)
      open(launchData.items[i].entry);
  } else {
    chrome.app.window.create('library.html', {
      id: "library",
      bounds: {
        width: 800,
        height: 600
      }
    });
  }
});
